//
//  AppTools.m
//  WIFI
//
//  Created by macbook on 2022/4/18.
//

#import "AppTools.h"
#import <CommonCrypto/CommonDigest.h>
#import "sys/utsname.h"
#import "UITabBar+Extension.h"
#import "AFNetworking.h"
#import "Reachability.h"
#import <Security/Security.h>
#import <Foundation/Foundation.h>
#import "LoginViewController.h"

// 钥匙串服务标识
static NSString *const kKeychainService = @"com.user.app.idfv";

@implementation AppTools

/**
 将字符串转成NSDate类型
 */
+ (NSDate *)dateFromString:(NSString *)dateString {
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *inputDate = [inputFormatter dateFromString:dateString];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: inputDate];
    NSDate *localeDate = [inputDate  dateByAddingTimeInterval: interval];
    
    return localeDate;
}

/**
 判断对象是否为空
 */
+ (BOOL)isEmpty:(id)object {
    if (object == nil || [object isEqual:[NSNull null]]) {
        return YES;
    }else if ([object isKindOfClass:[NSString class]]) {
        if ([object isEqualToString:@""]        ||
            [object isEqualToString:@"null"]    ||
            [object isEqualToString:@"nil"]     ||
            [object isEqualToString:@"(null)"]  ||
            [object isEqualToString:@"<null>"]  ||
            [object isEqualToString:@"(nil)"]   ||
            [object isEqualToString:@"<nil>"]) {
            return YES;
        }
        return [object isEqualToString:@""];
    }else if ([object isKindOfClass:[NSNumber class]]) {
        return [object isEqualToNumber:@(0)];
    }
    return NO;
}

/**
 MD5加密
 */
+ (NSString *)md5:(NSString *)string {
    const char* input = [string UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    
    return digest;
}

/**
 获取当前显示的视图控制器
 */
+ (UIViewController *)getCurrentVC {
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
        if (window.windowLevel != UIWindowLevelNormal) {
            NSArray *windows;
            if(@available(iOS 15.0, *)) {
                NSArray *array =[[[UIApplication sharedApplication] connectedScenes] allObjects];
                UIWindowScene* windowScene = (UIWindowScene*)array[0];
                windows = windowScene.windows;
            }else {
                windows = [[UIApplication sharedApplication] windows];
            }
            for (UIWindow * tmpWin in windows) {
                if (tmpWin.windowLevel == UIWindowLevelNormal) {
                    window = tmpWin;
                    break;
                }
            }
        }
        UIViewController *rootVC = window.rootViewController;
        UIViewController *activeVC = nil;
            
        while (true) {
            if ([rootVC isKindOfClass:[UINavigationController class]]) {
                activeVC = [(UINavigationController *)rootVC visibleViewController];
            } else if ([rootVC isKindOfClass:[UITabBarController class]]) {
                activeVC = [(UITabBarController *)rootVC selectedViewController];
            } else if (rootVC.presentedViewController) {
                activeVC = rootVC.presentedViewController;
            } else if (rootVC.childViewControllers.count > 0) {
                activeVC = [rootVC.childViewControllers lastObject];
            } else {
                break;
            }
            rootVC = activeVC;
        }
        return activeVC;
}

/**
 获取window
 */
+ (UIWindow *)getWindow {
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    
    return window;
}

/**
 获取当前时间 YYYY-MM-dd HH:mm:ss
 */
+ (NSString*)getCurrentTimes {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];

    return currentTimeString;
}

/**
 获取当前时间 自定义格式
 */
+ (NSString*)getCurrentTimesType:(NSString *)timeType {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:timeType];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];

    return currentTimeString;
}

/**
 传入今天的时间，返回明天的时间
 */
+ (NSString *)GetTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}


/**
 时间戳毫秒转日期
 */
+ (NSString *)UTCchangeDate:(NSString *)utc format:(NSString *)format {

    if (utc.length >= 13) {
        utc = [NSString stringWithFormat:@"%ld",utc.integerValue/1000];
    }
    
    if ([format isEqualToString:@""]) {
        format = @"YYYY-MM-dd HH:mm:ss";
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setDateFormat:format];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:utc.doubleValue];
    NSString *timeStr = [formatter stringFromDate:date];
    
    return timeStr;
}

/**
 日期转时间戳
 */
+ (NSString *)TimeToTimestampWtihString:(NSString *)time
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [formatter dateFromString:time];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}

/**
 日期转时间戳 自定义格式
 */
+ (NSString *)TimeToTimestampWtihString:(NSString *)time format:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [formatter dateFromString:time];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}

/**
 判断某个时间是否处于当天内
 */
+ (BOOL)validateWithDate:(NSDate *)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];
//    components.hour = 8;
    // 当天起始时间
    NSDate *startDate = [calendar dateFromComponents:components];
    // 当天结束时间
    NSDate *expireDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
    
    if ([date compare:startDate] == NSOrderedDescending && [date compare:expireDate] == NSOrderedAscending) {
        return YES;
    } else {
        return NO;
    }
}

/**
 获取当前时间戳
 */
+ (NSString *)getNowTimeTimestamp {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];

    return timeSp;

}

/**
 切割UIView左上角为圆角
 */
+ (CAShapeLayer *)clipTopLeftByRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}

/**
 切割UIView右上角为圆角
 */
+ (CAShapeLayer *)clipTopRightByRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopRight cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}

/**
 切割UIView左边两个角为圆角
 */
+ (CAShapeLayer *)clipAllCornersByRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}

/**
 切割UIView左边两个角为圆角
 */
+ (CAShapeLayer *)clipTopLeftAndLeftByRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}
/**
 切割UIView右边两个角为圆角
 */
+ (CAShapeLayer *)clipTopRightAndRightByRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}
/**
 切割UIView上面两个角为圆角
 */
+ (CAShapeLayer *)clipTopRightAndLeftByRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}

/**
 切割UIView全部角为圆角
 */
+ (CAShapeLayer *)clipAllRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}


/**
 切割UIView下面两个角为圆角
 */
+ (CAShapeLayer *)clipBottomRightAndLeftByRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}

/**
 切割UIView右下角为圆角
 */
+ (CAShapeLayer *)clipBottomRightByRoundingCorners:(UIView *)view radii:(CGSize)size {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomRight cornerRadii:size];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    
    return maskLayer;
}

/**
 json转字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        DLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

/**
 字典转json
 */
+ (NSString *)jsonStringWithDictionary:(NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        DLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@"" withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}

/**
 数组转json
 */
+ (NSString *)jsonStringWithNSArray:(NSArray *)arr {
    NSError *error = nil;
    if ([self isEmpty:arr]) {
        return @"";
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//    NSString *jsonS = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
    return jsonTemp;
}

/**
 json转数组
 */
+ (NSArray *)arrayWithJsonString:(NSString *)jsonStr {
    if (jsonStr) {
        id tmp = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        if (tmp) {
            if ([tmp isKindOfClass:[NSArray class]]) {
                return tmp;
            } else if([tmp isKindOfClass:[NSString class]]
                      || [tmp isKindOfClass:[NSDictionary class]]) {
                return [NSArray arrayWithObject:tmp];
            } else {
                return nil;
            }
        } else {
            return nil;
        }
    }else {
        return nil;
    }
}

/**
 改变字符串中某一段字符串的颜色和大小
 */
+ (NSMutableAttributedString *)setAttStringWithString:(NSString *)string changeString:(NSString *)changeString changeColor:(NSString *)changeColor changeFont:(UIFont *)changeFont {
    NSRange rangeRmb=[string rangeOfString:[NSString stringWithFormat:@"%@", changeString]];
    NSMutableAttributedString *rmbStr=[[NSMutableAttributedString alloc] initWithString:string attributes:nil];
    NSDictionary *fontDic=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHexString:changeColor],NSForegroundColorAttributeName,changeFont,NSFontAttributeName, nil];
    [rmbStr addAttributes:fontDic range:rangeRmb];
           
    return rmbStr;
}

/**
 根据文字和字体大小获取size
 */
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize {
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size;
}

+ (BOOL)isSimuLator {
    if (TARGET_IPHONE_SIMULATOR == 1 && TARGET_OS_IPHONE == 1) {
        //模拟器
        return YES;
    }else{
        //真机
        return NO;
    }
}

/**
 获取当前网络状态
-1.未知网络
 0.网络不可达
 1.蜂窝数据
 2.WIFI
 3.无网络
 */
+ (NSInteger)getCurrentNetworkStatus {
    __block NSInteger netType = 0;
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                netType = -1;
                break;
            case 0:
                netType = 0;
                break;
            case 1:
                netType = 1;
            break;
            case 2:
                netType = 2;
                break;
            default:
                break;
        }
    }];
    return netType;
}

/*
 即时获取当前网络状态
-1.未知网络
 0.网络不可达
 1.蜂窝数据
 2.WIFI
 3.无网络
 */
+ (NSInteger)reachabilityCurrentNetworkStatus {
    Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.apple.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    
    NSInteger status = 0;
    switch (internetStatus) {
            
        case ReachableViaWiFi:
            status = 2;
            break;
       
        case ReachableViaWWAN:
            status = 1;
            break;
       
        case NotReachable:
            status = 0;
            break;
           
        default:
            break;
   }
    return status;
}

/**
 获取当前时间的: 前一周(day:-7)丶前一个月(month:-30)丶前一年(year:-1)的时间戳
 */
+ (NSString *)getExpectTimestamp:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day {
 
    ///< 当前时间
    NSDate *currentdata = [NSDate date];
 
    ///< NSCalendar -- 日历类，它提供了大部分的日期计算接口，并且允许您在NSDate和NSDateComponents之间转换
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    /*
    ///<  NSDateComponents：时间容器，一个包含了详细的年月日时分秒的容器。
    ///< 下例：获取指定日期的年，月，日
    NSDateComponents *comps = nil;
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentdata];
    NSLog(@"年 year = %ld",comps.year);
    NSLog(@"月 month = %ld",comps.month);
    NSLog(@"日 day = %ld",comps.day);*/
 
    
    NSDateComponents *datecomps = [[NSDateComponents alloc] init];
    [datecomps setYear:year?:0];
    [datecomps setMonth:month?:0];
    [datecomps setDay:day?:0];
    
    ///< dateByAddingComponents: 在参数date基础上，增加一个NSDateComponents类型的时间增量
    NSDate *calculatedate = [calendar dateByAddingComponents:datecomps toDate:currentdata options:0];
    
    ///< 打印推算时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSString *calculateStr = [formatter stringFromDate:calculatedate];
    
    DLog(@"calculateStr 推算时间: %@",calculateStr );
 
    ///< 预期的推算时间
    NSString *result = [NSString stringWithFormat:@"%ld", (long)[calculatedate timeIntervalSince1970]];
    
    return result;
}

/*
 渐变色
 */
+ (void)createByCAGradientLayer:(UIColor *)startColor endColor:(UIColor *)endColor layerFrame:(CGRect)frame {
 
    CAGradientLayer *layer = [CAGradientLayer new];
    layer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
    layer.startPoint = CGPointMake(0.0, 0.0);
    layer.endPoint = CGPointMake(0.0, 1);
    layer.frame = frame;
    [[AppTools getCurrentVC].view.layer addSublayer:layer];
 
}

/*
 获取设备名
 */
+ (NSString *)getDeviceName {
    struct utsname systemInfo;

    uname(&systemInfo);

    NSString *deviceModel = [NSString stringWithFormat:@"Model: %s", systemInfo.sysname];

    return deviceModel;
}

/*
 保存IDFA
 */
+ (void)saveIDFA:(NSString *)idfa {
    [[NSUserDefaults standardUserDefaults] setObject:idfa forKey:@"USERIDFA"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/*
 读取IDFA
 */
+ (NSString *)getIDFA {
    NSString *idfa = [[NSUserDefaults standardUserDefaults] objectForKey:@"USERIDFA"];
    if ([AppTools isEmpty:idfa]) {
        return @"";
    }
    return idfa;
}

/*
 保存IDFV
 */
+ (BOOL)saveToKeychain:(NSString *)value {
    NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
    if (!data) return NO;
    
    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: kKeychainService,
        (__bridge id)kSecValueData: data,
        (__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleAfterFirstUnlock
    };
    
    // 先删除旧值
    SecItemDelete((__bridge CFDictionaryRef)query);
    
    // 添加新值
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
    return (status == errSecSuccess);
}

/*
 读取IDFV
 */
+ (NSString *)loadFromKeychain {
    NSDictionary *query = @{
        (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService: kKeychainService,
        (__bridge id)kSecReturnData: @YES,
        (__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne
    };
    
    CFTypeRef result = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
    
    if (status == errSecSuccess && result) {
        NSData *data = (__bridge_transfer NSData *)result;
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    
    return nil;
}

// 生成伪IDFA格式字符串 (XXXX-XXXX-XXXX-XXXX)
+ (NSString *)generatePseudoIDFA {
    NSMutableString *result = [NSMutableString string];
    
    // 生成32位十六进制字符串 (8-4-4-4-12)
    for (int i = 0; i < 32; i++) {
        if (i == 8 || i == 12 || i == 16 || i == 20) {
            [result appendString:@"-"];
        }
        uint32_t randomValue = arc4random_uniform(16); // 0-15
        unichar character = (randomValue < 10) ? ('0' + randomValue) : ('A' + (randomValue - 10));
        [result appendFormat:@"%C", character];
    }
    
    return result;
}

// 获取或创建IDFV
+ (NSString *)getOrCreatePseudoIDFV {
    NSString *storedIDFA = [self loadFromKeychain];
    
    if (!storedIDFA) {
        storedIDFA = [self generatePseudoIDFA];
        [self saveToKeychain:storedIDFA];
    }
    
    return storedIDFA;
}

/*
 获取登录token
 */
+ (NSString *)getLoginToken {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_token"];
    if ([AppTools isEmpty:token]) {
        return @"";
    }
    return token;
}

/*
 获取登录国家
 */
+ (NSString *)getLoginCountry {
    NSString *country = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_country"];
    if ([AppTools isEmpty:country]) {
        return @"";
    }
    return country;
}

/*
 是否是首次启动
 */
+ (BOOL)isFirstOpen {
    NSString *isFirst = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_is_first"];
    if ([AppTools isEmpty:isFirst]) {
        return YES;
    }else {
        return NO;
    }
}

/*
 是否登录
 */
+ (BOOL)isLogin {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_token"];
    if ([self isEmpty:token]) {
        return NO;
    }else {
        return YES;
    }
}

/*
 跳转到登录
 */
+ (void)toLogin {
    
    UITabBarController *tabBarController = [AppTools getCurrentVC].tabBarController;
    tabBarController.selectedIndex = 0;
    
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [[AppTools getCurrentVC] presentViewController:loginVC animated:NO completion:^{}];
}

@end
